package com.showcai.util;

import com.showcai.tools.ToolsBase;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.LinkedList;
import java.util.List;


public class ExcelOut extends ToolsBase {

    public static void excelOut(String fileName, HttpServletResponse resp, String[] strList, List<LinkedList<String>> list) {

        //创建HSSFWorkbook对象(excel的文档对象)
        HSSFWorkbook wb = new HSSFWorkbook();
        //建立新的sheet对象（excel的表单）
        HSSFSheet sheet=wb.createSheet("fileName");
        //创建单元格并设置单元格内容
        HSSFRow row2=sheet.createRow(0);

        for(int i = 0;i<strList.length;i++){
            row2.createCell(i).setCellValue(strList[i]);
        }
        if(list!=null){
            for(int i =1;i<=list.size();i++){
                sheet.createRow(i);
            }
            //在sheet里创建剩余行
            int i = 0;
            for (LinkedList list1:list){
                i++;
                for(int j = 0;j<strList.length;j++){
                    if(sheet.getRow(i)!=null){
                        if(j<list1.size()){
                            HSSFCell cell =  sheet.getRow(i).createCell( (short)j);
                            cell.setCellType(HSSFCell.CELL_TYPE_STRING);
                            cell.setCellValue((String)list1.get(j));
                        }
                    }
                }
            }
        }
        //输出Excel文件
        OutputStream output= null;
        try {
            output = resp.getOutputStream();
            resp.reset();
            resp.setHeader("Content-disposition", "attachment; filename="+fileName+".xls");
            resp.setContentType("application/msexcel");
            wb.write(output);
            output.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
